<template>
	<view class="container">
		<view class="title" @click="returnCertificate">
			<view class="icon"></view>
			<view class="text">单位申请</view>
		</view>
		<view class="content">
			<view class="content-title">
				<view class="line"></view>
				<span class="title-unit">上传公函申请</span>
				<span class="supplement">(格式为png/jpg,大小不能超过10mb)</span>
			</view>
			<up-upload
			    class="upload"
				:fileList="fileList1"
				@afterRead="afterRead"
				@delete="deletePic"
				maxSize="10485760"
				name="1"
				multiple
			></up-upload>
			<view class="content-title">
				<view class="line"></view>
				<span class="title-unit">联系方式</span>
			</view>
			<view class="info">
				<view class="title-info">
					手机号
				</view>
				<up-input
				  class="option"
				  border="bottom"
				  v-model="telephoneNum"
				  clearable
				  placeholder="请输入手机号"
				  @blur="validatePhone"
				></up-input>		
			</view>
			<view v-if="showError" class="error-message">
			  {{ errorText }}
			</view>
			<!-- 申请用途 -->
			<view class="apply-Purpose">
				<view class="line"></view>
				<span class="title-unit">申请用途</span>
			</view>
			<view class="applyInfo">
				<up-radio-group
				    v-model="applyPurpose"
					class="option"
				    placement="row">
					<up-radio
					  v-for="(item, index) in applyPurposeList"
					  :key="index"
					  :label="item.name"
					  :name="item.name"
					  @change="applyPurposeChange"
					>
					</up-radio>
				</up-radio-group>	
			</view>
			<view class="purposeDiy">
				<up-input v-if="showApplyPurposeDiy" v-model="applyPurposeDiy" placeholder="请填写详细的申请用途" border="bottom"></up-input>
			</view>
			<up-button class="confirm" type="primary" text="确定" @click="confirmInfo"></up-button>
		</view>
	</view>
	<!-- uview-plus 弹窗组件 -->
	<u-modal 
	  v-model:show="showModal"
	  :show-confirm-button="false"
	  :closeOnClickOverlay="true"
	  :zoom="true"
	>
	  <view class="success-modal-content">
		<!-- 成功图标 -->
		<view class="success-icon">
		  <u-icon 
			name="checkmark-circle-fill" 
			size="80" 
			color="#468BFB"
		  ></u-icon>
		</view>
		
		<!-- 成功文字 -->
		<view class="success-text">
		  <text class="title">申请成功</text>
		  <text class="subtitle">您的申请已提交成功，请耐心等待审核结果</text>
		</view>
		
		<!-- 操作按钮 -->
		<view class="button-group">
		  <u-button 
			type="primary" 
			shape="circle"
			@click="handleConfirm"
			customStyle="width: 100%; height: 80rpx;"
		  >
			确定
		  </u-button>
		</view>
	  </view>
	</u-modal>
</template>

<script setup>
import { ref, watch, reactive } from 'vue'
// 返回气象证明申请模块
const returnCertificate =()=>{
	uni.navigateTo({
	  url: '/pages/applicationCertificate/applicationCertificate'
	});
}

const fileList1 = ref([]);
const disasterPicUrl = ref([])
// 删除图片
const deletePic = (event) => {
  fileList1.value.splice(event.index, 1);
  //删除转换后的url
  disasterPicUrl.value.splice(event.index, 1)
};

// 新增图片
const afterRead = async (event) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = fileList1.value.length;
  lists.map((item) => {
    fileList1.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url);
    let item = fileList1.value[fileListLen];
    fileList1.value.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: result,
    });
    fileListLen++;
  }
};

const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: 'http://218.28.7.243:32201/api/files/multipleUpload',
      filePath: url,
      name: 'files',
      success: (res) => {
		console.log('res',res)
      	disasterPicUrl.value.push(JSON.parse(res.data).data[0])
        setTimeout(() => {
          resolve(res.data.data);
        }, 1000);
      },
    });
  });
};


//输入手机号
// 填写手机号
const telephoneNum = ref('')
const showError = ref(false)
const errorText = ref('请输入正确的手机号码')

const validatePhone = () => {
  // 更完善的手机号正则验证
  const phoneReg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/
  
  if (!telephoneNum.value.trim()) {
    showError.value = true
    errorText.value = '请输入手机号码'
    return false
  } else if (!phoneReg.test(telephoneNum.value)) {
    showError.value = true
    errorText.value = '请输入正确的手机号码'
    return false
  } else {
    showError.value = false
    return true
  }
}

// 监听输入变化，实时验证
watch(telephoneNum, (newVal) => {
  if (showError.value) {
    validatePhone()
  }
})

// 申请用途
const applyPurpose = ref('')
// 申请用途数据
const applyPurposeList = reactive([
  {
    name: '保险理赔',
    disabled: false,
  },
  {
    name: '事故调查',
    disabled: false,
  },
  {
    name: '诉讼需要',
    disabled: false,
  },
  {
    name: '科学研究',
    disabled: false,
  },
  {
    name: '其他',
    disabled: false,
  },
]);

// 是否展示申请用途-其他
const showApplyPurposeDiy = ref(false)
// 申请用途-其他
const applyPurposeDiy = ref('')

const applyPurposeChange = (n) => {
  applyPurpose.value = n
  //把选择的申请用途赋值给applyPurpose
  if(n!=='其他'){
	  showApplyPurposeDiy.value = false
	  console.log('选中的值', applyPurpose.value);
  }else{
	  showApplyPurposeDiy.value = true
	  applyPurposeDiy.value = ''
	  console.log('选中的值', applyPurpose.value);
  }
};

// 判断并返回对应的值
const getApplyPurposeValue = () => {
  // 检查applyPurpose是否为'其他'（不区分大小写的判断）
  if (applyPurpose.value === '其他') {
    return applyPurposeDiy.value
  } else {
    return applyPurpose.value
  }
}

// 验证函数
const validateApplyPurpose = () => {
  // 当选择了'其他'时
  if (applyPurpose.value === '其他') {
    // 检查自定义输入是否为空（去除首尾空格）
    return applyPurposeDiy.value.trim() !== '';
  } else {
    // 未选择'其他'时，检查applyPurpose是否有效
    const value = applyPurpose.value;
    // 不为空、不是undefined、不是null时返回true
    return value !== '' && value !== undefined && value !== null;
  }
};

// 检查 fileList1.value 的长度是否大于 0
const hasFilesInList1 = () => {
  return fileList1.value && fileList1.value.length > 0;
};

//确定上传
const confirmInfo = async ()=>{
	console.log('fileList1',fileList1.value.length)
	//判断输入数据完整性
	let isComplete = validateApplyPurpose()&&validatePhone()&&hasFilesInList1()
	//判断输入信息是否健全
	if(!isComplete){
		uni.showToast({
		  title: '请填写联系方式和申请用途,并上传公函', // 提示内容
		  icon: 'none', // 图标，可选值: success, loading, none
		  duration: 3000, // 显示时长(ms)，默认1500
		  position: 'center' // 位置，可选值: top, center, bottom
		});
		return
	}
	//单位申请逻辑
	await uni.request({
	  url: 'http://218.28.7.243:32201/api/wcertificate/orgApply', // 请求URL
	  method: 'POST',
	  header: {
	    'Access-Control-Allow-Origin': '*',
	  },
	  data:{
		wxId: telephoneNum.value,
		phoneNum: telephoneNum.value,
		appPurpose: getApplyPurposeValue(), //申请用途
		certificationUrl:disasterPicUrl.value.join(','),//服务器返回的上传图片url，将多个url拼接成字符串，用逗号分隔
	  },
	  success: (res) => {
		if(res.data.code==200){
			showModal.value = true
		}
	  },
	  fail: (err) => {
	    console.error('请求失败:', err);
		uni.showToast({
		  title: '提交失败，请重新提交或联系气象科技服务中心', // 提示内容
		  icon: 'none', // 图标，可选值: success, loading, none
		  duration: 2000, // 显示时长(ms)，默认1500
		  position: 'center' // 位置，可选值: top, center, bottom
		});
	  },
	  complete: () => {
	    console.log('请求完成');
	  }
	});	
}
// 申请成功弹窗
// 控制弹窗显示
const showModal = ref(false)

// 确认按钮点击事件
const handleConfirm = () => {
  console.log('用户点击了确定按钮')
  showModal.value = false
  // 这里可以添加其他业务逻辑
}

</script>

<style lang="scss" scoped>
	.container{
		position: relative;
		width: 100%;
		background-image: url('/static/background.png');
		background-size: 100% 100%;
		background-repeat: no-repeat;
		.title{
			position: relative;
			box-sizing: border-box;
			padding-top: 50rpx;
			padding-left: 20rpx;
			position: relative;
			width: 100%;
			height: 300rpx;
			display: flex;
			.icon{
				width: 40rpx;
				height: 40rpx;
				background-image: url('/static/unitIcon.png');
				background-size: 100% 100%;
				background-repeat: no-repeat;
			}
			.text{
				width: 144rpx;
				height: 40rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 36rpx;
				color: #181818;
				line-height: 36rpx;
				text-align: left;
				font-style: normal;
			}
		}
		.content{
			position: relative;
			width: 100%;
			background-color: #FFFFFF;
			border-top-right-radius: 25rpx;
			border-top-left-radius: 25rpx;
			.content-title{
				position: relative;
				width: 100%;
				box-sizing: border-box;
				padding: 30rpx 30rpx;
				display: flex;
				.line{
					position: relative;
					box-sizing: border-box;
					margin-right: 10rpx;
					width: 6rpx;
					height: 28rpx;
					background: #468BFB;
					border-radius: 0rpx 4rpx 4rpx 0rpx;
				}
				.title-unit{
					position: relative;
					// width: 180rpx;
					height: 28rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 30rpx;
					color: #181818;
					line-height: 28rpx;
					text-align: left;
					font-style: normal;
				}
				.supplement{
					position: relative;
					margin-left: auto;
					height: 28rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #B0B3BF;
					line-height: 28rpx;
					text-align: left;
					font-style: normal;
				}
			}
			.upload{
				position: relative;
				box-sizing: border-box;
				padding: 0 20rpx;
				width: 100%;
			}			
			.info{
				// height: 200rpx;
				position: relative;
				width: 100%;
				box-sizing: border-box;
				padding: 20rpx 20rpx;
				margin: 0;
				display: flex;
				justify-content: center;
				align-items: center;
				.title-info{
					flex: 1;
					text-align: center;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					color: #6E6D72;
					text-align: center;
					font-style: normal;
				}
				.option{
					flex: 4;
				}
			}
			.error-message { 
			  color: red;
			  font-size: 24rpx;
			  padding-left: 180rpx;
			  margin-top: -20rpx;
			  height: 40rpx;
			}
			.apply-Purpose{
				position: relative;
				width: 100%;
				box-sizing: border-box;
				padding: 30rpx 30rpx;
				display: flex;
				.line{
					position: relative;
					box-sizing: border-box;
					margin-right: 10rpx;
					width: 6rpx;
					height: 28rpx;
					background: #468BFB;
					border-radius: 0rpx 4rpx 4rpx 0rpx;
				}
				.title-unit{
					position: relative;
					// width: 180rpx;
					height: 28rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 30rpx;
					color: #181818;
					line-height: 28rpx;
					text-align: left;
					font-style: normal;
				}
			}
			.applyInfo{
				position: relative;
				width: 100%;
				box-sizing: border-box;
				padding: 20rpx 42rpx;
				margin: 0;
			}
			.purposeDiy{
				position: relative;
				width: 100%;
				box-sizing: border-box;
				padding: 20rpx 40rpx;
				margin: 0;
			}
			.confirm{
				position: relative;
				box-sizing: border-box;
				margin-top: 100rpx;
				width: 686rpx;
				height: 80rpx;
				background: linear-gradient( 180deg, #6FA4FD 0%, #468BFA 100%);
				border-radius: 16rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 80rpx;
				text-align: right;
				font-style: normal;
			}
		}
	}
	.success-modal-content {
	  padding: 40rpx;
	  text-align: center;
	  
	  .success-icon {
	    margin-bottom: 30rpx;
	    display: flex;
	    justify-content: center;
	  }
	  
	  .success-text {
	    margin-bottom: 40rpx;
	    
	    .title {
	      display: block;
	      font-size: 36rpx;
	      font-weight: bold;
	      color: #333;
	      margin-bottom: 20rpx;
	    }
	    
	    .subtitle {
	      display: block;
	      font-size: 28rpx;
	      color: #666;
	      line-height: 1.5;
	    }
	  }
	  
	  .button-group {
	    margin-top: 20rpx;
	  }
	}
</style>